package com.tanhua.dubbo.api.mongo;

import com.tanhua.domain.mongo.Friend;
import com.tanhua.domain.mongo.RecommendUser;
import com.tanhua.domain.mongo.Visitor;
import com.tanhua.domain.vo.PageResult;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class FriendApiImpl implements FriendApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 添加联系人
     *
     * @param loginUserId
     * @param userId
     */
    @Override
    public void makeFriends(Long loginUserId, Long userId) {
        //1. 添加登录用户与佳人
        long timeMillis = System.currentTimeMillis();
        Friend friend = new Friend();
        friend.setUserId(loginUserId);
        friend.setFriendId(userId);
        friend.setCreated(timeMillis);
        // 判断是否存在
        // 构建查询条件
        Query query = new Query(Criteria.where("userId").is(loginUserId).and("friendId").is(userId));
        if (!mongoTemplate.exists(query, Friend.class)) {
            // 不存在则要添加
            mongoTemplate.insert(friend);
        }

        //2. 添加佳人与登录用户
        friend = new Friend();
        friend.setUserId(userId);
        friend.setFriendId(loginUserId);
        friend.setCreated(timeMillis);
        query = new Query(Criteria.where("userId").is(userId).and("friendId").is(loginUserId));
        if (!mongoTemplate.exists(query, Friend.class)) {
            // 不存在则要添加
            mongoTemplate.insert(friend);
        }
    }

    /**
     * 分页查询登录用户的好友
     *
     * @param loginUserId
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public PageResult findPage(Long loginUserId, Long page, Long pageSize) {
        //1. 构建查询的条件userId=登录用户id
        Query query = new Query(Criteria.where("userId").is(loginUserId));
        //2. 统计总数
        long total = mongoTemplate.count(query, Friend.class);
        List<Friend> friendList = new ArrayList<>();
        //3. 总数>0
        if (total>0) {
            //4. 设置分页参数
            query.skip((page-1)*pageSize).limit(pageSize.intValue());
            //5. 查询
            friendList = mongoTemplate.find(query, Friend.class);
        }
        //6. 构建pageResult返回
        return PageResult.pageResult(page,pageSize,friendList, total);
    }

    /**
     * 根据用户id统计好友个数
     *
     * @param userId
     * @return
     */
    @Override
    public long countByUserId(Long userId) {
        //1. 构建查询条件
        Query query = new Query(Criteria.where("userId").is(userId));
        //2. 统计总数
        long total = mongoTemplate.count(query, Friend.class);
        return total;
    }

    /**
     * 分页查询好友+缘分值
     *
     * @param userId
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public PageResult findPageWithScore(Long userId, Long page, Long pageSize) {
        //1.先分页查询好友
        Query query = new Query(Criteria.where("userId").is(userId));
        long total = mongoTemplate.count(query, Friend.class);

        List<RecommendUser> recommendUserListSort = new ArrayList<>();
        if(total > 0){
            // 设置分页参数
            query.skip((page-1)*pageSize).limit(pageSize.intValue());
            // 按时间降序
            query.with(Sort.by(Sort.Order.desc("created")));
            List<Friend> friendList = mongoTemplate.find(query, Friend.class);
            if(!CollectionUtils.isEmpty(friendList)) {
                //2.再查登录用户与好友的缘分
                //2.1 获取所有好友的Id
                List<Long> friendIds = friendList.stream().map(Friend::getFriendId).collect(Collectors.toList());
                Query recommendUserQuery = new Query(Criteria.where("toUserId").is(userId)
                        .and("userId").in(friendIds));
                //2.2 查登录用户与好友的缘分
                List<RecommendUser> recommendUserList = mongoTemplate.find(recommendUserQuery, RecommendUser.class);
                // 转成map key=好友的id, value=RecommendUser
                Map<Long, RecommendUser> recommendUserMap = recommendUserList.stream()
                        .collect(Collectors.toMap(RecommendUser::getUserId, ru -> ru));
                // 转成保留顺序的结果集
                for (Friend friend : friendList) {
                    RecommendUser ru = recommendUserMap.get(friend.getFriendId());
                    recommendUserListSort.add(ru);
                }
            }
        }
        return PageResult.pageResult(page, pageSize, recommendUserListSort,total);
    }
}
